package com.party.mem.web.controller.xzgs;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.city.Area;
import com.party.core.model.city.City;
import com.party.core.model.commune.*;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherFormInfo;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.*;
import com.party.core.service.city.IAreaService;
import com.party.core.service.city.ICityService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.commune.ICMemberRecommendService;
import com.party.core.service.commune.impl.CIntegralBizService;
import com.party.core.service.commune.impl.CIntegralItemService;
import com.party.core.service.commune.impl.CUserIntegralService;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.member.IIndustryService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.PartnerMemberToBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.mem.biz.member.CIntegralBizToService;
import com.party.mem.biz.member.MemberMgmtService;
import com.party.mem.biz.member.XzgsMemberBizService;
import com.party.mem.biz.system.member.MemberBizService;
import com.party.mem.biz.system.member.MemberGroupBizService;
import com.party.mem.utils.RealmUtils;
import com.party.mem.utils.excel.ExportExcel;
import com.party.mem.web.annotation.UserOperate;
import com.party.mem.web.dto.AjaxResult;
import com.party.mem.web.dto.common.MemberDetailsType;
import com.party.mem.web.dto.output.member.MemberMgmtOutput;
import com.party.mem.web.dto.output.member.ProjectForMembermUserOutput;
import com.party.mem.web.security.CurrentUser;
import org.apache.commons.lang.ArrayUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 行知公社会员管理
 * @Author: yangshoukun
 * @Date: 2018/2/22 10:56
 */
@Controller
@RequestMapping(value = "member/membermgmt")
public class XzgsMemberMgmtController {

    @Autowired
    private MemberMgmtService memberMgmtService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private ICMemberInfoService memberInfoService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private ICMemberRecommendService memberRecommendService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private ICityService cityService;
    @Autowired
    private CIntegralBizService integralBizService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @Autowired
    private CIntegralBizToService cIntegralBizToService;

    @Autowired
    private CIntegralItemService cIntegralItemService;
    @Autowired
    private CUserIntegralService userIntegralService;

    @Autowired
    private ICIntegralTypeService integralTypeService;

    @Autowired
    private IGatherProjectService gatherProjectService;
    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private IGatherFormService gatherFormService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;
    @Autowired
    private PartnerMemberToBizService partnerMemberToBizService;
    @Autowired
    private XzgsMemberBizService xzgsMemberBizService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;

    Logger logger = LoggerFactory.getLogger(getClass());


    @RequestMapping(value = "list")
    public ModelAndView list(MemberMgmtQuery input, Page page) {

        CurrentUser member = RealmUtils.getNewCurrentUser();

        page.setLimit(10);
        ModelAndView mv = new ModelAndView("xzgs/xzgsmember");

        //设置行知公社表单项目id
        String projectBy = memberGroupService.getPartnerId(member.getId()) + "kc";

        GatherProject project = gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_KC_MEMBER, projectBy);

        if (null == input.getType()) {
            input.setType(0);
        }
        //自定义表单项业务
        boolean hasProject = false;

        if (project != null && input.getType() != Integer.valueOf(1)) {
            input.setProjectId(project.getId());
            List<String> titles = gatherFormService.getAllTitleByProjectId(project.getId());
            input.setTitles(titles);

            mv.addObject("titles", JSONObject.toJSON(titles));

            hasProject = true;
            mv.addObject("projectId", project.getId());
        }
        List<MemberGroup> memberGroupList = new ArrayList<>();
        if (!member.isChild()) {
            memberGroupList = memberGroupService.getChildWithMyAndName(member.getId());
            mv.addObject("memberGroupList", memberGroupList);
            if (StringUtils.isEmpty(input.getMemberGroupId())) {
                input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
            }
        }

        if (!Constant.MEMBER_XZGSADMIN.equals(member.getType())) {
            List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
            input.setOrgIds(orgIds);
        } else {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(member.getId(), member.getPartnerId());
        }
        mv.addObject("memberGroupList", memberGroupList);
        //是否拥有行知公社权限
        boolean isCommune = cIntegralBizToService.isXZGSJurisdiction(member.getId());
        mv.addObject("isCommune", isCommune);

        Map<Integer, String> types = MemberMgmtType.convertMap();
        mv.addObject("types", types);

        mv.addObject("isXzgsAdmin", member.isXzgsAdmin());
        mv.addObject("input", input);
        mv.addObject("partnerId", member.getId());
        mv.addObject("isChild", member.isChild());
        mv.addObject("projectBy", projectBy);
        mv.addObject("hasProject", hasProject);
        mv.addObject("page",page);
        return mv;

    }

    /**
     * @param input
     * @param page
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author shenliuhai
     * @date 2019/12/13 17:21
     */
    @ResponseBody
    @RequestMapping(value = "/xzgs/api/list")
    public Map<String, Object> ajaxData(MemberMgmtQuery input, Page page) {

        page.setLimit(10);
        CurrentUser member = RealmUtils.getNewCurrentUser();

        //获取父级id
        String parentId = memberGroupService.getPartnerId(member.getId());


        //设置行知公社表单项目id
        String projectBy = parentId + "kc";

        GatherProject project = gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_KC_MEMBER, projectBy);

        if (null == input.getType()) {
            input.setType(0);
        }
        //自定义表单项业务

        if (project != null && input.getType() != Integer.valueOf(1)) {
            input.setProjectId(project.getId());
            List<String> titles = gatherFormService.getAllTitleByProjectId(project.getId());
            input.setTitles(titles);
        }

        if (!member.isChild() && StringUtils.isEmpty(input.getMemberGroupId())) {
            input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
        }
        //获取积分类型
        //户外
        String outdoorId = xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.OUTDOOR_TYPE).getId();
        //学习
        String studyId = xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.STUDY_TYPE).getId();
        //奉献
        String devoteId = xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.DEVOTE_TYPE).getId();
        //公益
        String publicWelfareId =
                xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.PULICE_WELFARE_TYPE).getId();

        input.setOutdoorId(outdoorId);
        input.setStudyId(studyId);
        input.setDevoteId(devoteId);
        input.setPublicWelfareId(publicWelfareId);

        //获取行知公社id
        String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
        input.setXzgsMemberId(xzgsMemberId);

        if (!Constant.MEMBER_XZGSADMIN.equals(member.getType())) {
            List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
            input.setOrgIds(orgIds);
        }

        //会员管理只显示审核通过的会员
        input.setCheckStatus(YesNoStatus.YES.getCode());

        List<Map<String, Object>> list = memberMgmtService.list(input, "", page);

        List<MemberMgmtOutput> memberMgmtOutputs = LangUtils.transform(list, new Function<Map<String, Object>, MemberMgmtOutput>() {

            @Override
            public MemberMgmtOutput apply(Map<String, Object> map) {
                MemberMgmtOutput output = new MemberMgmtOutput();

                output.setUserSerial((String) map.get("userSerial"));
                output.setNickName((String) map.get("nickName"));
                output.setSex((String) map.get("sex"));
                output.setMobile((String) map.get("mobile"));
                output.setWechatNum((String) map.get("wechatNum"));
                output.setCompany((String) map.get("company"));
                output.setJob((String) map.get("job"));
                output.setArea((String) map.get("area"));
                output.setCreateTime((String) map.get("createTime"));
                output.setLogo((String) map.get("logo"));
                output.setRealname((String) map.get("realname"));
                //分社职位
                output.setLeagueJob((String) map.get("leagueJob"));
                //最近一次参加活动时间
                output.setLastJoinActTime(String.valueOf(map.get("lastJoinActTime")));
                //推荐人数
                output.setMemRecommends(String.valueOf(map.get("memRecommends")));
                //行动力
                output.setMemberActionForce(map.get("memberActionForce").toString());
                //影响力
                output.setMemberInfluenceForce(map.get("memberInfluenceForce").toString());
                //户外
                output.setOutdoorIntegral(map.get("outdoorIntegral").toString());
                //奉献
                output.setDevoteIntegral(map.get("devoteIntegral").toString());
                //学习
                output.setStudyIntegral( map.get("studyIntegral").toString());
                //公益
                output.setPublicWelfareIntegral( map.get("publicWelfareIntegral").toString());

                Integer checkStatus = (Integer) map.get("checkStatus");

                if (Integer.valueOf("0").equals(checkStatus)) {
                    output.setCheckStatus("待审核");
                } else if (Integer.valueOf("1").equals(checkStatus)) {
                    output.setCheckStatus("审核通过");
                } else {
                    output.setCheckStatus("审核拒绝");
                }

                //获取保存在主分社的二维码路径
                String memberId = map.get("memberId").toString();
                String partnerId = map.get("partnerId").toString();
                String pmId = map.get("pmId").toString();

                output.setMemberId(memberId);
                output.setPmId(pmId);
                output.setPartnerId(partnerId);

                Map<String, Object> customField = new HashMap<>();
                List<String> feildList = memberMgmtService.titleList();
                for (String title : feildList) {
                    customField.put(title, map.get(title) == null ? "" : map.get(title));
                }
                output.setCustomField(customField);

                return output;
            }
        });

        Map<String, Object> ret = Maps.newHashMap();

        ret.put("data", memberMgmtOutputs);
        ret.put("count", page.getTotalCount());
        ret.put("code", 0);
        ret.put("page",page);
        return ret;
    }


    /**
     * @param input
     * @param response
     * @Description: 会员管理表格数据导出
     * @Author: huangwuming
     * @Date: 2018/2/27 10:56
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_LISTEXPORT)
    @ResponseBody
    @RequestMapping(value = "xzgs/listExport")
    public AjaxResult listExport(MemberMgmtQuery input, HttpServletResponse response) {
        String headName = "";
        if (input.getType() == 0) {
            headName = "会员管理";
        }
        if (input.getType() == 1) {
            headName = "用户管理";
        }
        String fileName = headName + DateUtils.todayDate() + ".xlsx";

        MemberGroup member = RealmUtils.getCurrentUser();
        //String partnerId = member.getId();

        String projectBy = memberGroupService.getPartnerId(member.getId()) + "kc";

        GatherProject project = gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_KC_MEMBER, projectBy);

        if (null == input.getType()) {
            input.setType(0);
        }
        //自定义表单项业务
        List<String> titles = new ArrayList<>();
        if (project != null) {
            input.setProjectId(project.getId());
            titles = gatherFormService.getAllTitleByProjectId(project.getId());
            input.setTitles(titles);
        }
        if (!Constant.MEMBER_XZGSADMIN.equals(member.getType())) {
            List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
            input.setOrgIds(orgIds);
        }
        //获取父级id
        String parentId = memberGroupService.getPartnerId(member.getId());

        //获取积分类型
        //户外
        String outdoorId = xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.OUTDOOR_TYPE).getId();
        //学习
        String studyId = xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.STUDY_TYPE).getId();
        //奉献
        String devoteId = xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.DEVOTE_TYPE).getId();
        //公益
        String publicWelfareId =
                xzgsMemberBizService.getIntegralByType(parentId,XzgsMemberBizService.PULICE_WELFARE_TYPE).getId();

        input.setOutdoorId(outdoorId);
        input.setStudyId(studyId);
        input.setDevoteId(devoteId);
        input.setPublicWelfareId(publicWelfareId);

        //获取行知公社id
        String xzgsMemberId = memberGroupBizService.getXzgsMemberId();
        input.setXzgsMemberId(xzgsMemberId);

        if (StringUtils.isEmpty(input.getMemberGroupId())) {
            input.setPartnerType(PartnerMember.IS_MAIN_TYPE);
        }
        List<Map<String, Object>> list = memberMgmtService.list(input, "", null);
        try {
            ExportExcel exportExcel = null;
            //设置会员导出的excel表头单元格
            if (input.getType() == 0) {
                List<String> headerList = new ArrayList<>();
                headerList.add("编号");
                headerList.add("昵称");
                headerList.add("性别");
                headerList.add("手机号");
                headerList.add("微信号");
                headerList.add("公司");
                headerList.add("区域");
                headerList.add("职务");
                headerList.add("加入时间");
                headerList.add("所属机构");
                headerList.add("审核状态");
                headerList.add("分社职位");
                headerList.add("最近参加活动时间");
                headerList.add("行动力");
                headerList.add("影响力");
                headerList.add("户外积分");
                headerList.add("公益积分");
                headerList.add("贡献积分");
                headerList.add("学习积分");
                headerList.add("推荐人数");
                for (String title : titles) {
                    headerList.add(title);
                }
                exportExcel = new ExportExcel(fileName,headerList);

                exportExcel = memberMgmtService.setDataList(list, exportExcel, input, titles);
                String allPath = memberMgmtService.getExcelPath(fileName, "membermgmt", exportExcel);

                return AjaxResult.success((Object) allPath);
            }
            //设置用户导出的excel表头单元格
            if (input.getType() == 1) {
                exportExcel = new ExportExcel(fileName, ProjectForMembermUserOutput.class);
                exportExcel = memberMgmtService.setDataList(list, exportExcel, input, null);
                String allPath = memberMgmtService.getExcelPath(fileName, "membermgmt", exportExcel);
                return AjaxResult.success((Object) allPath);
            }

        } catch (IOException e) {
            logger.error("导出会员异常", e);
        }
        return AjaxResult.error("导出异常");
    }




    @RequestMapping(value = "/xzgs/form")
    public ModelAndView form(String pmId, String pageNo) {

        ModelAndView mv = new ModelAndView("xzgs/cmemberForm");
        Member member = null;
        CMemberInfo memberInfo = null;
        Member tjMember = null;
        String city = null;
        String arParent = null;

        String industryId = null;
        String idParent = null;
        if (StringUtils.isNotEmpty(pmId)) {
            //用户
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            member = memberService.get(partnerMember.getMemberId());
            //用户详细信息
            memberInfo = memberInfoService.getByMemberId(partnerMember.getMemberId());
            //推荐人
            PartnerMember mainOrg = partnerMemberService.getMainOrg(partnerMember.getMemberId(), partnerMember.getPartnerId());
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setuId(mainOrg.getId());
            List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
            if (list.size() > 0) {
                CMemberRecommend cMemberRecommend1 = list.get(0);
                PartnerMember tj_partnerMember = partnerMemberService.get(cMemberRecommend1.getParentId());
                tjMember = memberService.get(tj_partnerMember.getMemberId());
            }
            //地区
            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                if (area != null) {
                    city = area.getId();
                    arParent = area.getParentId();
                }
            }
            //行业
            if (StringUtils.isNotEmpty(member.getIndustry())) {
                Industry industry = industryService.get(member.getIndustry());
                if (industry != null) {
                    industryId = industry.getId();
                    idParent = industry.getParentId();
                }
            }
            if (memberInfo == null) {
                memberInfo = new CMemberInfo();
            }
            //用户编号
            memberInfo.setUserSerial(mainOrg.getUserSerial());
        }

        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);

        City city1 = new City();
        city1.setIsOpen(1);
        mv.addObject("citys", cityService.list(city1));


        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);

        mv.addObject("city", city);
        mv.addObject("arParent", arParent);

        mv.addObject("industryId", industryId);
        mv.addObject("idParent", idParent);

        mv.addObject("member", member);
        mv.addObject("pmId", pmId);
        mv.addObject("tjMember", tjMember);
        mv.addObject("memberInfo", memberInfo);
        mv.addObject("pageNo",pageNo);
        return mv;
    }


    @RequestMapping(value = "/xzgs/details")
    public ModelAndView details(String pmId, String type, String pageNo) {

        ModelAndView mv = new ModelAndView("xzgs/cmemberDetailsForm");
        Member member = null;
        CMemberInfo memberInfo = null;
        Member tjMember = null;
        String city = null;
        String arParent = null;

        String industryId = null;
        String idParent = null;
        if (StringUtils.isNotEmpty(pmId)) {
            //用户
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            member = memberService.get(partnerMember.getMemberId());
            //用户详细信息
            memberInfo = memberInfoService.getByMemberId(partnerMember.getMemberId());
            //推荐人
            PartnerMember mainOrg = partnerMemberService.getMainOrg(partnerMember.getMemberId(), partnerMember.getPartnerId());
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setuId(mainOrg.getId());
            List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
            if (list.size() > 0) {
                CMemberRecommend cMemberRecommend1 = list.get(0);
                PartnerMember tj_partnerMember = partnerMemberService.get(cMemberRecommend1.getParentId());
                tjMember = memberService.get(tj_partnerMember.getMemberId());
            }
            //地区
            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                if (area != null) {
                    city = area.getId();
                    arParent = area.getParentId();
                }
            }
            //行业
            if (StringUtils.isNotEmpty(member.getIndustry())) {
                Industry industry = industryService.get(member.getIndustry());
                if (industry != null) {
                    industryId = industry.getId();
                    idParent = industry.getParentId();
                }
            }
            if (memberInfo == null) {
                memberInfo = new CMemberInfo();
            }
            //用户编号
            memberInfo.setUserSerial(partnerMember.getUserSerial());

            //个人信息公司信息
            MemberMgmtOutput companyInfoOutput =  memberMgmtService.getMemberCompanyInfo(partnerMember);

            //一对一分析信息
            memberMgmtService.getQuestionInfo(mv,member.getId());

            mv.addObject("xzgsMemberInfo",companyInfoOutput);


        }

        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);

        City city1 = new City();
        city1.setIsOpen(1);
        mv.addObject("citys", cityService.list(city1));


        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);

        mv.addObject("city", city);
        mv.addObject("arParent", arParent);

        mv.addObject("industryId", industryId);
        mv.addObject("idParent", idParent);

        mv.addObject("member", member);
        mv.addObject("pmId", pmId);
        mv.addObject("tjMember", tjMember);
        mv.addObject("memberInfo", memberInfo);

        mv.addObject("detailType",type);
        if (StringUtils.isEmpty(type)) {
            mv.addObject("detailType",0);
        }

        Map<Integer, String> detailsTypes = MemberDetailsType.convertMap();
        mv.addObject("detailsTypes",detailsTypes);
        mv.addObject("pageNo",pageNo);
        return mv;
    }

    @RequestMapping(value = "xzgs/xzgsInfos")
    @ResponseBody
    public AjaxResult getXzgsInfo(String pmId, Integer type) {
        if (StringUtils.isEmpty(pmId)) {
            return AjaxResult.error("参数为空");
        }
        PartnerMember partnerMember = partnerMemberService.get(pmId);
        if (Integer.valueOf(1).equals(type)) {
            //行知公社有关信息
            MemberMgmtOutput xzgsInfo = xzgsMemberBizService.getXzgsMemberInfo(partnerMember);
            return AjaxResult.success(xzgsInfo);
        }

        return AjaxResult.success();
    }

    /**
     * @Description: 编辑用户
     * @Param: [input, request]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_UPDATE)
    @ResponseBody
    @RequestMapping(value = "/xzgs/saveOrUpdate")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(CMemberInfo input) {

        if (StringUtils.isEmpty(input.getLogo())) {
            return AjaxResult.error("用户头像为空");
        }
        if (StringUtils.isEmpty(input.getRealname())) {
            return AjaxResult.error("用户姓名为空");
        }
        if (StringUtils.isEmpty(input.getMobile())) {
            return AjaxResult.error("用户手机号为空");
        }
        try {
            if (StringUtils.isNotEmpty(input.getUserSerial())) {
                String userSerial = input.getUserSerial().trim();
                PartnerMember queryPartnerMember = new PartnerMember();
                queryPartnerMember.setUserSerial(userSerial);
                List<PartnerMember> list = partnerMemberService.list(queryPartnerMember);
                if (list.size() > 0) {
                    PartnerMember pmOrg = list.get(0);
                    if (!pmOrg.getId().equals(input.getPmId())) {
                        return AjaxResult.error("已存在相同的编号");
                    }
                }
                input.setUserSerial(userSerial);
            }

            memberBizService.saveOrUpdateCmember(input);
        } catch (Exception e) {
            logger.error("编辑用户异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑用户异常", e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * @Description: 获取用户信息
     * @Param: [memberId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @ResponseBody
    @RequestMapping(value = "/xzgs/getcMemberInfo")
    public AjaxResult getcMemberInfo(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error("参数为空");
        }
        try {
            Map<String, Object> mmp = Maps.newHashMap();

            String arParent = "";

            String partnerId = RealmUtils.getCurrentUser().getId();

            Member member = memberService.get(memberId);
            if (StringUtils.isNotEmpty(member.getCity())) {
                Area area = areaService.get(member.getCity());
                arParent = area.getParentId();
            }
            CMemberInfo cMemberInfo = memberInfoService.getByMemberId(memberId);
            PartnerMember partnerMember = partnerMemberService.
                    findByPartnerAndMember(partnerId, memberId);
            if (cMemberInfo == null) {
                cMemberInfo = new CMemberInfo();
            }
            if (partnerMember != null) {
                cMemberInfo.setUserSerial(partnerMember.getUserSerial());
            }
            mmp.put("member", member == null ? new Member() : member);
            mmp.put("cMemberInfo", cMemberInfo == null ? new CMemberInfo() : cMemberInfo);
            mmp.put("arParent", arParent);
            return AjaxResult.success(mmp);
        } catch (Exception e) {
            logger.error("获取用户信息异常", e);
            return AjaxResult.error("获取用户信息异常", e.getMessage());
        }
    }


    /**
     * @Description:审核用户
     * @Param: [memberId, state]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/10/29
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_CHECK)
    @ResponseBody
    @RequestMapping(value = "/xzgs/checkMember")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult checkMember(String pmId, Integer state) {
        if (StringUtils.isEmpty(pmId) || null == state) {
            return AjaxResult.error("参数不能为空");
        }
        try {
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            String memberId = partnerMember.getMemberId();
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();
            String partnerId = currentUser.getId();
            if (currentUser.isChild()) {
                partnerId = currentUser.getPartnerId();
            }
            Member member = memberService.get(memberId);
            CMemberInfo byMemberId = memberInfoService.getByMemberId(memberId);
            if (byMemberId == null || member == null) {
                return AjaxResult.error("用户信息不存在");
            }
            if (CMemberInfo.CHECK_STATUS_ADOPT == byMemberId.getCheckStatus()) {
                return AjaxResult.error("用户已审核完成");
            }
            if (CMemberInfo.CHECK_STATUS_ADOPT == state) {
                byMemberId.setCheckStatus(CMemberInfo.CHECK_STATUS_ADOPT);

                //如果存在推荐关系即插入推荐积分
//                PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(partnerId, memberId);
                CMemberRecommend cMemberRecommend = new CMemberRecommend();
                cMemberRecommend.setuId(partnerMember.getId());
                List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
                if (list.size() > 0) {
                    try {
                        CMemberRecommend cMemberRecommend1 = list.get(0);
                        PartnerMember partnerMember1 = partnerMemberService.get(cMemberRecommend1.getParentId());
                        integralBizService.insertSystemCIntegralItem(cMemberRecommend1.getId(), partnerId, partnerMember1, null, IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
                    } catch (Exception e) {
                        logger.error("插入推荐积分异常", e.getMessage());
                    }
                }
                try {
                    integralBizService.insertSystemCIntegralItem(null, partnerId, partnerMember, null, IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
                } catch (Exception e) {
                    logger.error("插入赠送积分异常", e.getMessage());
                }
            }
            if (CMemberInfo.CHECK_STATUS_REJECT == state) {
                byMemberId.setCheckStatus(CMemberInfo.CHECK_STATUS_REJECT);

                //将手机号设为空，让用户重新走注册流程
                member.setMobile("");
                memberService.update(member);
            }
            memberInfoService.update(byMemberId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("用户审核异常", e);
            return AjaxResult.error("用户审核异常");
        }
    }


    /**
     * 分配分社
     */
    @RequestMapping(value = "/xzgs/setTag")
    public ModelAndView getTag(String memberId, String partnerId) {
        if (StringUtils.isEmpty(memberId)) {
            return null;
        }
        ModelAndView mv = new ModelAndView("xzgs/setMemberTag");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        List<String> orgIds = memberGroupService.getChild(currentUser.getId());
        List<MemberGroup> memberGroupList = new ArrayList<>();
        for (String id : orgIds) {
            MemberGroup memberGroup = memberGroupService.get(id);
            memberGroupList.add(memberGroup);
        }
        //获得主分社id
        PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, partnerId);

        String mainPartenrId = "";
        if (mainOrg != null) {
            mainPartenrId = mainOrg.getPartnerId();
        } else {
            PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerId, memberId);
            byPartnerAndMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
            partnerMemberService.update(byPartnerAndMember);
            mainPartenrId = byPartnerAndMember.getPartnerId();
        }

        //获取次分社ids
        String partnerIds = "";
        List<PartnerMember> memberPartners = new ArrayList<>();
        List<String> ids = memberGroupService.getChildWithMy(currentUser.getId());
        for (String id : ids) {
            PartnerMember ciPartenr = new PartnerMember();
            ciPartenr.setMemberId(memberId);
            ciPartenr.setPartnerId(id);
            ciPartenr.setPartnerType(0);
            List<PartnerMember> list = partnerMemberService.getMemberPartners(ciPartenr);
            if (list.size() > 0) {
                memberPartners.add(list.get(0));
            }
        }
        for (PartnerMember member : memberPartners) {
            partnerIds += member.getPartnerId() + ",";
        }

        mv.addObject("partnerIds", partnerIds);
        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("memberId", memberId);
        mv.addObject("mainPartenrId", mainPartenrId);

        return mv;
    }

    /***
     * 修改会员所属分社
     * @Date 20:30 2019/11/14
     * @param ids 已选次分社
     * @param partnerIds 原有次分社
     * @param memberId 会员ID
     * @param partnerMainIds 已选主分社
     * @param partnerMainId 原来主分社
     * @return
     **/
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_ASSIGN_BRANCH)
    @ResponseBody
    @RequestMapping(value = "/xzgs/changeAccout")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public AjaxResult changeAccout(String ids, String partnerIds, String memberId, String partnerMainIds, String partnerMainId) {

        if (StringUtils.isEmpty(memberId) || StringUtils.isEmpty(partnerMainIds)) {
            return AjaxResult.error("主分社必须选择一个");
        }

        try {
            //相比原来所属机构新增的机构关系
            List<String> addList = new ArrayList<>();
            //相比原来所属机构减少的机构关系
            List<String> deleteList = new ArrayList<>();

            //会员要移动到机构ids
            String[] updateIds = ids.split(",");

            //会员原来所属机构ids
            String[] orginIds = partnerIds.split(",");

            //会员主分社的机构id
            String[] memberPartnerMainIds = partnerMainIds.split(",");
            String memberPartnerMainId = memberPartnerMainIds[0];

            for (String orginId : orginIds) {
                if (StringUtils.isNotEmpty(orginId)) {
                    if (!ArrayUtils.contains(updateIds, orginId)) {
                        deleteList.add(orginId);
                    }
                }
            }

            for (String updateId : updateIds) {
                if (StringUtils.isNotEmpty(updateId)) {
                    if (!ArrayUtils.contains(orginIds, updateId)) {
                        addList.add(updateId);
                    }
                }
            }

            //原来主分社移动到次分社
            boolean addFlag = addList.contains(partnerMainId);
            if (addFlag) {
                addList.remove(partnerMainId);
            }
            //原来次分社移动到主分社
            boolean delFlag = deleteList.contains(memberPartnerMainId);
            if (delFlag) {
                deleteList.remove(memberPartnerMainId);
            }

            boolean result = false;

            //相比于原所属机构，增加的机构id
            String[] addArr = addList.toArray(new String[addList.size()]);
            //相比于原所属机构，减少的机构id
            String[] deleteArr = deleteList.toArray(new String[deleteList.size()]);

            //主分社修改
            if (StringUtils.isNotEmpty(partnerMainId) && !memberPartnerMainId.equals(partnerMainId)
                    && !addFlag && !delFlag) {
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerId(memberPartnerMainId);
                partnerMemberService.update(byPartnerAndMember);

                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }
            if (addFlag && !delFlag) {
                //修改原主分社为次分社
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerType(0);
                partnerMemberService.update(byPartnerAndMember);

                //添加主分社
                PartnerMember partnerMember = new PartnerMember();
                partnerMember.setMemberId(memberId);
                partnerMember.setPartnerId(memberPartnerMainId);
                partnerMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                partnerMemberService.insert(partnerMember);

                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }

            if (!addFlag && delFlag) {

                //删除原来主分社
                PartnerMember byPartnerAndMember1 = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                //该会员所邀请的人
                CMemberRecommend cMemberRecommend = new CMemberRecommend();
                cMemberRecommend.setParentId(byPartnerAndMember1.getId());
                List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
                //邀请该会员的人
                CMemberRecommend uMember = new CMemberRecommend();
                uMember.setuId(byPartnerAndMember1.getId());
                List<CMemberRecommend> uList = memberRecommendService.list(uMember);
                if (list.size() > 0 || uList.size() > 0) {
                    Member member = memberService.get(memberId);
                    MemberGroup memberGroup = memberGroupService.get(partnerMainId);
                    throw new BusinessException(member.getRealname() + "在" + memberGroup.getRealname() + "机构下有推荐的人，不能被移除");
                }
                partnerMemberService.delete(byPartnerAndMember1.getId());

                //修改次分社为主分社
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(memberPartnerMainId, memberId);
                byPartnerAndMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                partnerMemberService.update(byPartnerAndMember);
                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }

            if (addFlag && delFlag) {
                //主分社和次分社互换
                PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partnerMainId, memberId);
                byPartnerAndMember.setPartnerType(0);
                partnerMemberService.update(byPartnerAndMember);

                PartnerMember byPartnerAndMember1 = partnerMemberService.findByPartnerAndMember(memberPartnerMainId, memberId);
                byPartnerAndMember1.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                partnerMemberService.update(byPartnerAndMember1);

                //重新生成小程序二维码
                cIntegralBizToService.generateXZGSXCXQRCode(memberPartnerMainId, memberId);

                result = true;
            }

            if (addArr.length == 0 && deleteArr.length == 0 && memberPartnerMainId.equals(partnerMainId)) {
                return AjaxResult.error("没有更改，不用分配");
            } else if (addArr.length == deleteArr.length) {
                //添加和减少的机构相等，不用删除，直接修改partnerId
                for (int i = 0; i < addArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    byPartnerAndMember.setPartnerId(addArr[i]);
                    byPartnerAndMember.setPartnerType(0);
                    partnerMemberService.update(byPartnerAndMember);
                }
                result = true;
            } else if (addArr.length == 0 && deleteArr.length > 0) {
                //只有减少，没有增加，直接删除
                for (String partenrId : deleteArr) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(partenrId, memberId);
                    //该会员邀请的人
                    CMemberRecommend cMemberRecommend = new CMemberRecommend();
                    cMemberRecommend.setParentId(byPartnerAndMember.getId());
                    List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
                    //邀请该会员的人
                    CMemberRecommend uMember = new CMemberRecommend();
                    uMember.setuId(byPartnerAndMember.getId());
                    List<CMemberRecommend> uList = memberRecommendService.list(uMember);
                    if (list.size() > 0 || uList.size() > 0) {
                        Member member = memberService.get(memberId);
                        MemberGroup memberGroup = memberGroupService.get(partenrId);
                        throw new BusinessException(member.getRealname() + "在" + memberGroup.getRealname() + "机构下有推荐的人，不能被移除");
                    }
                    partnerMemberService.delete(byPartnerAndMember.getId());
                }
                result = true;
            } else if (addArr.length > 0 && deleteArr.length == 0) {
                //只有增加，没有减少，直接添加
                for (String partenrId : addArr) {
                    PartnerMember partnerMember = new PartnerMember();
                    partnerMember.setMemberId(memberId);
                    partnerMember.setPartnerId(partenrId);
                    partnerMember.setPartnerType(0);
                    partnerMemberService.insert(partnerMember);
                }
                result = true;
            } else if (addArr.length > deleteArr.length) {
                //增加的多于删除的，部分更改partnerId，部分新增
                for (int i = 0; i < deleteArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    byPartnerAndMember.setPartnerId(addArr[i]);
                    //不是主分社
                    byPartnerAndMember.setPartnerType(0);
                    partnerMemberService.update(byPartnerAndMember);
                }
                for (int i = deleteArr.length; i < addArr.length; i++) {
                    PartnerMember partnerMember = new PartnerMember();
                    partnerMember.setMemberId(memberId);
                    partnerMember.setPartnerId(addArr[i]);
                    partnerMember.setPartnerType(0);
                    partnerMemberService.insert(partnerMember);
                }
                result = true;
            } else if (addArr.length < deleteArr.length) {
                //删除的多余增加的，更改部分partnerId,其余的直接删除

                for (int i = addArr.length; i < deleteArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    //该会员邀请的人
                    CMemberRecommend cMemberRecommend = new CMemberRecommend();
                    cMemberRecommend.setParentId(byPartnerAndMember.getId());
                    List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
                    //邀请该会员的人
                    CMemberRecommend uMember = new CMemberRecommend();
                    uMember.setuId(byPartnerAndMember.getId());
                    List<CMemberRecommend> uList = memberRecommendService.list(uMember);
                    if (list.size() > 0 || uList.size() > 0) {
                        Member member = memberService.get(memberId);
                        MemberGroup memberGroup = memberGroupService.get(deleteArr[i]);
                        throw new BusinessException(member.getRealname() + "在" + memberGroup.getRealname() + "机构下有推荐的人，不能被移除");
                    }
                    partnerMemberService.delete(byPartnerAndMember.getId());
                }

                for (int i = 0; i < addArr.length; i++) {
                    PartnerMember byPartnerAndMember = partnerMemberService.findByPartnerAndMember(deleteArr[i], memberId);
                    byPartnerAndMember.setPartnerId(addArr[i]);
                    byPartnerAndMember.setPartnerType(0);
                    partnerMemberService.update(byPartnerAndMember);
                }
                result = true;
            }
            if (result) {
                redisTokenManager.delRelationshipByKey(memberId);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("更改会员所属机构失败");
            }

        } catch (BusinessException b) {
            logger.error("更改会员所属机构失败", b);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(b.getMessage());
        } catch (Exception e) {
            logger.error("更改会员所属机构失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更改机构关系失败");
        }
    }

    /**
     * @Description:绑定推荐关系视图
     * @Param: [memberId]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/11/20
     */
    @RequestMapping(value = "/xzgs/bindingRRView")
    public ModelAndView bindingRRView(String memberId) {
        if (StringUtils.isEmpty(memberId)) {
            return null;
        }
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        //推荐类型的积分项
        List<CIntegralItem> cIntegralItems = null;
        //推荐人
        Member tjMember = null;
        //积分
        CUserIntegral cUserIntegral = null;
        //积分项
        CIntegralItem cIntegralItem = null;
        try {
            //主机构
            PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, currentUser.getId());
            //推荐的人
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setuId(mainOrg.getId());
            List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
            if (list.size() > 0) {
                CMemberRecommend crOrg = list.get(0);

                //获取推荐的人
                PartnerMember partnerMember = partnerMemberService.get(crOrg.getParentId());
                tjMember = memberService.get(partnerMember.getMemberId());

                //获取推荐的人对应加的积分
                CUserIntegral cuiOrg = new CUserIntegral();
                cuiOrg.setRecommendId(crOrg.getId());
                List<CUserIntegral> list1 = userIntegralService.list(cuiOrg);
                cUserIntegral = list1.get(0);
                //对应的积分项
                cIntegralItem = cIntegralItemService.get(cUserIntegral.getIntegralItemId());
            }

            //积分项列表
            String partnerId = memberGroupService.getPartnerId(currentUser.getId());
            CIntegralType cIntegralType = new CIntegralType();
            cIntegralType.setCategory(IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
            cIntegralType.setCreateBy(partnerId);
            List<CIntegralType> cIntegralTypes = integralTypeService.list(cIntegralType);
            if (cIntegralTypes.size() > 0) {
                cIntegralType = cIntegralTypes.get(0);
            } else {
                throw new BusinessException("没有找到推荐类型的积分类型");
            }
            CIntegralItem ciiOrg = new CIntegralItem();
            ciiOrg.setCreateBy(partnerId);
            ciiOrg.setTypeId(cIntegralType.getId());
            cIntegralItems = cIntegralItemService.list(ciiOrg);

        } catch (Exception e) {
            logger.error("查看推荐关系异常", e.getMessage());
            return null;
        }
        ModelAndView mv = new ModelAndView("xzgs/bindingRRView");
        mv.addObject("memberId", memberId);
        mv.addObject("tjMember", tjMember);
        mv.addObject("cUserIntegral", cUserIntegral);
        mv.addObject("cIntegralItem", cIntegralItem);
        mv.addObject("cIntegralItems", cIntegralItems);
        return mv;
    }

    /**
     * @Description:绑定推荐关系
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_RECOMMEND_INSERT)
    @ResponseBody
    @RequestMapping(value = "/xzgs/bindingRR", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult bindingRR(String cuserId, String memberId, String tjMemberId, String integralItemId, String tjMemberMobile) {

        if (StringUtils.isEmpty(memberId) ||
                (StringUtils.isEmpty(tjMemberMobile) && StringUtils.isEmpty(tjMemberId)) ||
                StringUtils.isEmpty(integralItemId)) {
            return AjaxResult.error("参数为空");
        }

        try {
            if (StringUtils.isNotEmpty(cuserId)) {
                /*                  修改推荐积分*/
                CUserIntegral cUserIntegral = userIntegralService.get(cuserId);
                if (!integralItemId.equals(cUserIntegral.getIntegralItemId())) {
                    cUserIntegral.setIntegralItemId(integralItemId);
                    userIntegralService.update(cUserIntegral);
                }
            } else {
                /*                  绑定推荐关系*/

                MemberGroup currentUser = RealmUtils.getCurrentUser();
                //当前登录机构id
                String orgId = currentUser.getId();
                //主机构id
                String partnerId = orgId;
                if (StringUtils.isNotEmpty(currentUser.getPartnerId())) {
                    partnerId = currentUser.getPartnerId();
                }

                CIntegralItem cIntegralItem = cIntegralItemService.get(integralItemId);
                if (null == cIntegralItem) {
                    return AjaxResult.error("积分项不存在");
                }
                if (memberId.equals(tjMemberId)) {
                    return AjaxResult.error("推荐人不能是当前用户");
                }
                if (StringUtils.isEmpty(tjMemberId)) {
                    List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
                    List<Map<String, Object>> list = memberService.findPartnerMemberByPhoneOrName2("phone", tjMemberMobile, Member.MEMBER_PERSONAL, orgIds);
                    if (list.size() == 0) {
                        return AjaxResult.error("推荐人不存在");
                    } else {
                        Map<String, Object> mmp = list.get(0);
                        tjMemberId = mmp.get("id").toString();
                    }
                }


                /*   判断是否存在 相互推荐*/
                //主分社
                PartnerMember mainOrg = partnerMemberService.getMainOrg(memberId, orgId);
                //推荐人主分社
                PartnerMember tj_mainOrg = partnerMemberService.getMainOrg(tjMemberId, orgId);

                /* 推荐关系绑定*/
                CMemberRecommend newMemberRecommend = new CMemberRecommend();
                newMemberRecommend.setuId(mainOrg.getId());
                newMemberRecommend.setParentId(tj_mainOrg.getId());
                List<CMemberRecommend> list = memberRecommendService.list(newMemberRecommend);
                if (list.size() == 0) {
                    CMemberRecommend cMemberRecommend = new CMemberRecommend();
                    cMemberRecommend.setParentId(mainOrg.getId());
                    cMemberRecommend.setuId(tj_mainOrg.getId());
                    List<CMemberRecommend> t_list = memberRecommendService.list(cMemberRecommend);
                    if (t_list.size() > 0) {
                        return AjaxResult.error("不能相互推荐");
                    }
                    //插入推荐关系
                    memberRecommendService.insert(newMemberRecommend);
                }
                //插入推荐积分
                integralBizService.insertSystemCIntegralItem(newMemberRecommend.getId(), partnerId, tj_mainOrg, cIntegralItem.getId(), IntegralType.CINTEGRALTYPE_CATEGORY_RECOMMEND.getCode());
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑积分异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑积分异常");
        }
    }


    /**
     * 自定义表单
     *
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @author shenliuhai
     * @date 2019/12/9 10:18
     */
    @RequestMapping("/xzgs/customFrom")
    public ModelAndView customFrom(String projectBy) {
        if (StringUtils.isEmpty(projectBy)) {
            return null;
        }
        ModelAndView mv = new ModelAndView("xzgs/customForm");

        GatherProject gatherProject = new GatherProject();
        gatherProject.setDelFlag(String.valueOf('0'));
        String createBy = projectBy;
        GatherProject project = gatherProjectService.findByCreateIdAndType(GatherProject.TYPE_KC_MEMBER, createBy);
        if (project != null) {
            Map<String, Object> resultMap = gatherProjectBizService.getFormItems(project.getId(), project.getQuantity());
            mv.addAllObjects(resultMap);
        }
        mv.addObject("project", project);
        mv.addObject("createBy", createBy);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "/xzgs/project/save", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(GatherProject gatherProject) {
        try {
            List<String> newFieldIds = Lists.newArrayList();

            if (StringUtils.isNotEmpty(gatherProject.getContent())) {
                String content = StringUtils.escapeHtml4Iframe2Video(gatherProject.getContent().trim());
                gatherProject.setContent(content);
            }

            String projectId = gatherProject.getId();
            String currentId = gatherProject.getCreateBy();
            if (StringUtils.isEmpty(gatherProject.getShowPicture())) {
                gatherProject.setShowPicture("2");
            }
            if (StringUtils.isNotEmpty(gatherProject.getId())) {
                GatherProject dbProject = gatherProjectService.get(gatherProject.getId());
                MyBeanUtils.copyBeanNotNull2Bean(gatherProject, dbProject);
                gatherProjectService.update(dbProject);
                currentId = dbProject.getCreateBy();
            } else {
                // 默认不通知
                gatherProject.setIsRemindMe("2");
                gatherProject.setCreateBy(currentId);
                gatherProject.setUpdateBy(currentId);
                //行知公社业务
                gatherProject.setType(GatherProject.TYPE_KC_MEMBER);
                gatherProject.setQuantity(0L);
                projectId = gatherProjectService.insert(gatherProject);

            }
            gatherProjectBizService.saveFormItems(gatherProject.getItems(), projectId, currentId, newFieldIds);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存会员表单项异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        }
    }

    @RequestMapping("/xzgs/customUpdateForm")
    public ModelAndView customUpdateForm(String memberId, String projectId, String pageNo) {
        ModelAndView mv = new ModelAndView("xzgs/customFormUpdate");

        if (StringUtils.isEmpty(memberId) || StringUtils.isEmpty(projectId)) {
            return null;
        }

        GatherProject project = gatherProjectService.get(projectId);
        boolean isNew = true;
        if (project != null) {
            List<GatherForm> fieldName = gatherProjectBizService.getFormItems(projectId, true);
            List<GatherFormInfo> fieldValue = gatherFormInfoService.getFormInfoByMemberId(memberId, projectId);
            if (fieldValue.size() > 0) {
                isNew = false;
            }
            mv.addObject("fieldName", fieldName);
            mv.addObject("fieldValue", fieldValue);
            mv.addObject("isNew", isNew);
        }
        mv.addObject("memberId", memberId);
        mv.addObject("projectId", projectId);
        mv.addObject("pageNo",pageNo);
        return mv;
    }

    /**
     * 保存会员的自定义表单信息
     * @author shenliuhai
     * @date 2019/12/23 14:38
     * @param project
     * @param memberId
     * @param isNew
     * @return com.party.web.web.dto.AjaxResult
     */
    @UserOperate(moduleName = "会员", behaviorType = BehaviorType.MEMBER_CUSTOM_FROM_UPDATE)
    @RequestMapping("/xzgs/saveMemberFieldValue")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveMemberFieldValue(GatherProject project, String memberId, boolean isNew) {
        if (StringUtils.isEmpty(project.getId())) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
        }
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "会员id不能为空");
        }
        String targetId = memberId + "kc";
        try {
            GatherProject gatherProject = gatherProjectService.get(project.getId());
            if (null == gatherProject) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "项目不存在");
            }
            GatherProject dbProject = gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getId(), memberId, targetId, isNew);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("信息保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "信息保存失败");
        }
    }

    /**
     * 保存会员一对一分析信息
     * @author shenliuhai
     * @date 2019/12/23 14:38
     * @param project
     * @param memberId
     * @param isNew
     * @return com.party.web.web.dto.AjaxResult
     */
    @RequestMapping("/xzgs/savaQuestionField")
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult savaQuestionField(GatherProject project, String memberId, boolean isNew) {
        if (StringUtils.isEmpty(project.getId())) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
        }
        if (StringUtils.isEmpty(memberId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "会员id不能为空");
        }
        String targetId = memberId + "QA";
        try {
            GatherProject gatherProject = gatherProjectService.get(project.getId());
            if (null == gatherProject) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "项目不存在");
            }
            GatherProject dbProject = gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getId(), memberId, targetId, isNew);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("问卷信息保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "问卷信息保存失败");
        }
    }
    /**
     * @Description: 手机号验证
     * @Param: [ mobile,  memberId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @ResponseBody
    @RequestMapping(value = "xzgs/checkPartnerUserMobile")
    public AjaxResult checkPartnerUserMobile(String mobile, String memberId) {
        if (StringUtils.isEmpty(mobile)) {
            return AjaxResult.error("参数为空");
        }
        try {
            //可以保存返回true,反之false
            String partnerId = RealmUtils.getCurrentUser().getId();
            boolean b = partnerMemberToBizService.checkPartnerUser(partnerId, memberId, mobile);
            return AjaxResult.success(b);
        } catch (Exception e) {
            logger.error("获取用户信息异常", e);
            return AjaxResult.error("获取用户信息异常", e.getMessage());
        }
    }
}
